<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- bootstrap用于布局 -->
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"
      crossorigin="anonymous"
    />

    <style>
      .pagination {
        justify-content: flex-end;
      }
    </style>
  </head>
  <body>
    <!-- container是页面具有响应式 -->
    <div class="container">
      <div>
        <!-- 搜索的表单 -->
        <form class="form-inline" style="float: left">
          <div class="form-group mb-2">
            <input
              type="text"
              class="form-control"
              id="username"
              placeholder="请搜索姓名"
            />
          </div>
          <button type="submit" class="btn btn-primary mb-2 search">
            搜索
          </button>
          <button type="reset" class="btn mb-2 reset">重置</button>
        </form>
        <button
          class="btn btn-primary mb-2"
          style="float: right"
          data-toggle="modal"
          data-target="#exampleModal"
        >
          新增
        </button>
      </div>

      <table class="table table-bordered">
        <thead>
          <tr>
            <th scope="col">姓名</th>
            <th scope="col">年龄</th>
            <th scope="col">性别</th>
            <th scope="col">住址</th>
            <th scope="col">电话</th>
            <th scope="col">操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>

      <nav aria-label="Page navigation example">
        <ul class="pagination"></ul>
      </nav>

      <!-- Modal模态框 -->
      <div
        class="modal fade"
        id="exampleModal"
        tabindex="-1"
        aria-labelledby="exampleModalLabel"
        aria-hidden="true"
      >
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">新增学员</h5>
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                aria-label="Close"
              >
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form>
                <div class="form-group">
                  <label for="name">姓名</label>
                  <input type="text" class="form-control" id="name" />
                </div>
                <div class="form-group">
                  <label for="age">年龄</label>
                  <input type="number" class="form-control" id="age" />
                </div>
                <div class="form-group">
                  <label for="sex">性别</label>
                  <select class="form-control" id="sex">
                    <option value="1">男</option>
                    <option value="2">女</option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="address">住址</label>
                  <input type="text" class="form-control" id="address" />
                </div>
                <div class="form-group">
                  <label for="phone">手机号</label>
                  <input type="number" class="form-control" id="phone" />
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-secondary"
                data-dismiss="modal"
              >
                取消
              </button>
              <button
                type="button"
                class="btn btn-primary"
                onclick="add()"
                data-dismiss="modal"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"
      crossorigin="anonymous"
    ></script>

    <script>
      const BASE_URL = "http://localhost:3000";
      let page = 1;
      const size = 2;

      // 将请求数据封装成promise
      const ajax = (url, data = {}, method = "GET") => {
        return new Promise((resolve, reject) => {
          $.ajax({
            url: BASE_URL + url,
            method: method,
            data: {
              ...data,
              token: localStorage.getItem("token"),
            },
            success(res) {
              resolve(res);
            },
          });
        });
      };

      // 请求列表
      const getTableDate = async (data = {}) => {
        const res = await ajax("/students/list", {
          ...data,
          page: page,
          size: size,
          token: localStorage.getItem("token"),
        });
        if (res.status === 0) {
          // 表格做拼接
          let str = "";
          res.result.forEach((item) => {
            str += `
              <tr>
                <th>${item.name}</th>
                <td>${item.age}</td>
                <td>${item.sex === 1 ? "男" : "女"}</td>
                <td>${item.address}</td>
                <td>${item.phone || ""}</td>
                <td>
                  <button type="button" class="btn btn-warning" onclick="getone('${
                    item._id
                  }')">编辑</button>
                  <button type="button" class="btn btn-danger" onclick="del('${
                    item._id
                  }')">删除</button>  
                </td>
              </tr>
            `;
          });
          $("tbody").html(str);

          // 分页做拼接
          let str2 =
            '<li class="page-item"><a class="page-link" href="#">Previous</a></li>';
          const pages = Math.ceil(res.count / size);
          for (let i = 0; i < pages; i++) {
            str2 += `<li class="page-item"><a class="page-link" href="#" onclick="fn(${
              i + 1
            })">${i + 1}</a></li>`;
          }
          str2 +=
            '<li class="page-item"><a class="page-link" href="#">Next</a></li>';
          $(".pagination").html(str2);
        } else if (res.status === 9999) {
          alert(res.msg);
        }
      };

      // 进页面请求数据
      window.onload = async () => {
        getTableDate();
      };

      // 点击搜索按钮
      $(".search").on("click", (e) => {
        e.preventDefault();
        const name = $("#username").val();
        page = 1;
        getTableDate({ name });
      });

      // 重置
      $(".reset").on("click", () => {
        getTableDate();
      });

      // 分页
      const fn = (i) => {
        page = i;
        getTableDate();
      };

      // 删除功能
      const del = async (id) => {
        const res = await ajax("/students/del", { id }, "POST");
        // console.log(res);
        if (res.status === 0) {
          // 删除成功
          getTableDate();
        } else {
          alert(res.msg);
        }
      };

      // 新增功能
      const add = async () => {
        const res = await ajax(
          "/students/add",
          {
            name: $("#name").val(),
            age: $("#age").val(),
            sex: $("#sex").val(),
            address: $("#address").val(),
            phone: $("#phone").val(),
          },
          "POST"
        );
        if (res.status === 0) {
          getTableDate();
        }
      };

      // 获取单个学员信息
      const getone = async (id) => {
        const res = await ajax("/students/get", { id: id }, "POST");
        console.log(res);
      };
    </script>
  </body>
</html>
